const fs = require("fs");
const path = require("path");
const { setCache, deleteCache, getAllCatch } = require("../utils/cache");
const schedule = require("node-schedule");

// 要读取的文件名
const file = "SchedulerTasks.json"; // 定时任务配置文件路径

class TaskScheduler {
  constructor() {
    this.tasks = {}; // 存储任务名称与任务的映射关系
  }

  // 添加定时任务
  addTask(taskName, cronExpression, callback, fromCatch) {
    if (this.tasks[taskName]) {
      console.log(`定时任务 ${taskName} 已存在`);
      return;
    }
    if (!fromCatch) {
      setCache(file, taskName, {
        taskName,
        cronExpression,
        callback: callback.toString(),
      });
    }

    const task = schedule.scheduleJob(cronExpression, callback);
    this.tasks[taskName] = task;
  }

  // 移除指定的定时任务
  removeTask(taskName) {
    const task = this.tasks[taskName];
    if (task) {
      task.cancel();
      deleteCache(file, taskName);
      delete this.tasks[taskName];
    }
  }

  // 加载并恢复之前的定时任务
  loadTasks() {
    const tasksConfig = getAllCatch(file);
    console.log(tasksConfig, "tasksConfig--");
    if (tasksConfig) {
      tasksConfig.forEach(({ name, cronExpression, callback }) => {
        // 重新添加定时任务
        this.addTask(
          name,
          cronExpression,
          (callback = new Function("return (" + callback + ")")()),
          true
        );
      });
    }
  }

  // 清空所有定时任务
  clearTasks() {
    Object.values(this.tasks).forEach((task) => task.cancel());
    this.tasks = {};
  }
}
const scheduler = new TaskScheduler();
scheduler.loadTasks();
module.exports = {
  scheduler,
};
